<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Crypt;
use Hash;
use DB;

class UserController extends Controller
{
    //用户添加页面
    public function add()
    {
    	$title = '用户添加';
    	return view('admin.user.add',['title' => $title]);
    }

    //用户执行添加页面
    public function insert(Request $request)
    {
    	$data = $request -> except('_token','email','pic');

         //检测用户名唯一的返回
        $ures = DB::table('user') -> where('username',$data['username']) -> first();
        if($ures)
        {
            return back() -> with('error','用户名 ' . $data['username'] . ' 已存在');
        }
        // dd($data);
    	//判断用户名是否为空
    	// if(empty($data['username']) || empty($data['password']))
    	// {
    	// 	return back() -> with(['username' => '用户名不能为空','password' => '密码不能为空']);
    	// }

        //设置限制条件
    	$this -> validate($request, [
    			          'username' => 'required|max:18',
    			          'password' => 'required',
    			        'repassword' => 'required|same:password',
    			             'email' => 'required|email',
    			             'phone' => 'required',
    		],[
    			 'username.required' => '用户名不能为空',
    			      'username.max' => '用户名不能超过18位',
    			 'password.required' => '密码不能为空',
    		   'repassword.required' => '确认密码不能为空',
    			   'repassword.same' => '两次密码不一致',
    			    'email.required' => '邮箱不能为空',
    		           'email.email' => '邮箱格式不正确',
    			    'phone.required' => '手机号不能为空',

    		]);

		// 删除repassword
		unset($data['repassword']);
		//加密密码
		$data['password'] = Crypt::encrypt($data['password']);
		// $data['password'] = Hash::make($data['password']);
		
        //判断status值
        if($data['quanxian'] == '普通用户')
        {
            $data['quanxian'] = 1;
        }else
        {
            $data['quanxian'] = 2;
        }

		//处理status
		$data['status'] = 1;
		//处理token
		$data['token'] = str_random(50);
        $data['atime'] = time();
        // dd($data);
		//执行添加返回添加的id
		$id = DB::table('user') -> insertGetId($data);
        // dd($id);
        if(!$id)
        {
            return back() -> with('error','添加失败');
        }

        //获取email与图片
        $data_b = $request -> only('email','pic');
        // dd($data_b);

        //处理pic
        if($request -> hasFile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                //获取后缀名
                $suffix = $request -> file('pic') -> getClientOriginalExtension();
                // echo $suffix;
                //随机文件名
                $fileName = time().mt_rand(100000,999999).'.'.$suffix;
                // $path = date('Ymd');
                $path = './uploads';
                $request -> file('pic') -> move($path,$fileName);

                $data_b['pic'] = trim($path.'/'.$fileName,'.');
                // echo $data['pic'];    
            }
        }

        //处理uid
        $data_b['uid'] = $id;
        //执行添加到关联表
        $res = DB::table('user_detail') -> insert($data_b);
		//判断
		if($res)
		{
			return redirect('/admin/user/index') -> with('success','添加成功');
		}else
		{
			return back() -> with('error','添加失败');
		}


    	 // dd($data);
    }

    //判断用户名是否唯一
    public function checkuser(Request $request)
    {

        $data = $request -> except('_token');
        //查询数据库是否有该用户名
        $res = DB::table('user') -> where('username',$data['username']) -> first();
        if($res)
        {
            return $msg = '用户名 ' . $data['username'] . ' 已存在';
        }else{
            return $msg = 0;
        }

    }

    //用户列表页
    public function index(Request $request)
    {
        $title = '用户列表';

        //查询数据
        $data = DB::table('user') -> where(function($query) use ($request){
                $query -> where('username','like','%'.$request -> input('keywords').'%');
        }) -> paginate($request -> input('num',10));




    	return view('admin.user.index',['title' => $title,'data' => $data,'request' => $request -> all()]);
    }

    //用户编辑
    public function edit($id)
    {
        $title = '用户编辑';
        $data = DB::table('user') -> where('id','=',$id) -> first();
        //查询关联表
        $data_b = DB::table('user_detail') -> where('uid','=',$id) -> first();
        // var_dump($data);
        $arr = explode(',', $data_b -> address);
        // var_dump($arr);
        // die();
        //解析模板
        return view('admin.user.edit',['title' => $title,'data' => $data,'data_b' => $data_b,'arr' => $arr]);

        
    }

    //用户更新
    public function update(Request $request)
    {

        $data = $request -> except('_token','oldpic','email','pic','id','age','sex','s_province','s_city','s_county','jiedao');
        // dd($data);
        $id = $request -> only('id');
// dd($id);
        //设置限制条件
        $this ->validate($request, [
                         'username' => 'required|max:18',
                            'email' => 'required|email',
                            'phone' => 'required',
            ],[
                'username.required' => '用户名不能为空',
                     'username.max' => '用户名不能超过18位',
                   'email.required' => '邮箱不能为空',
                      'email.email' => '邮箱格式不正确',
                   'phone.required' => '手机号不能为空',

            ]);

        //判断status值
        if($data['status'] == '启用')
        {
            $data['status'] = 1;
        }else
        {
            $data['status'] = 2;
        }

        //判断权限的值
        if($data['quanxian'] == '普通用户')
        {
            $data['quanxian'] = 1;
        }else
        {
            $data['quanxian'] = 2;
        }

        //向用户表添加数据
        $res1 = DB::table('user') -> where('id',13) -> update($data);

        $data_b = $request -> except('_token','oldpic','username','phone','id','atime','status','quanxian','s_province','s_city','s_county','jiedao');
        // dd($data_b);

        
        //处理address (收货地址)
        $data_add = $request -> only('s_province','s_city','s_county','jiedao');
        // dd($data_add);
        $data_b['address'] = $data_add['s_province'] . ','. $data_add['s_city']. ',' . $data_add['s_county']. ',' . $data_add['jiedao'];

        //获取老图片地址
        $oldpath = '.'.$request -> input('oldpic');

        //处理pic
        if($request -> hasFile('pic'))
        {
            if($request -> file('pic') -> isValid())
            {
                //获取后缀名
                $suffix = $request -> file('pic') -> getClientOriginalExtension();
                // echo $suffix;
                //随机文件名
                $fileName = time().mt_rand(100000,999999).'.'.$suffix;
                // $path = date('Ymd');
                $path = './uploads';
                $request -> file('pic') -> move($path,$fileName);

                $data_b['pic'] = trim($path.'/'.$fileName,'.');
                // echo $data['pic'];
               
                //判断有老图片删除
                if(file_exists($oldpath))
                {
                    unlink($oldpath);
                }
                
            }
        }

        //判断sex值
        if($data_b['sex'] == '男')
        {
            $data_b['sex'] = 1;
        }else
        {
            $data_b['sex'] = 2;
        }
         
         //向关联表添加数据
        $res2 = DB::table('user_detail') -> where('uid',$id) -> update($data_b);
      
        //判断
        if($res1 || $res2)
        {
            return redirect('/admin/user/index') -> with(['success' => '更新成功']);
        }else
        {
            return back() -> with(['error' => '更新失败']);
        }
    }

    //删除
    public function delete($id)
    {
        //删除用户表与关联表数据
        $res1 = DB::table('user') -> where('id',$id) -> delete();
        $res2 = DB::table('user_detail') -> where('uid',$id) -> delete();
        if($res1 && $res2)
        {
            return redirect('/admin/user/index') -> with(['success' => '删除成功']);
        }else
        {
            return back() -> with(['error' => '删除失败']);
        }
    }
}
